package com.ows.powercontrol.Listener.socket;


import com.ows.powercontrol.service.impl.CommonServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.Socket;

/**
 * @author cq
 */

public class ServerslistenerT implements Runnable {

    private int port;
    //    private String host="127.0.0.1";
    private String host;
//
//    private Socket socket;


    public ServerslistenerT(int port, String host) {
        this.port = port;
        this.host = host;
    }

    @Override
    public void run() {
        try {
            BufferedReader bufferedReader;
            if (CommonServiceImpl.socket==null){
                CommonServiceImpl.socket = new Socket(host, port);
            }
            while (true) {
                try {
//                    心跳包
                    try {
                        Writer writer = new OutputStreamWriter(CommonServiceImpl.socket.getOutputStream());
                        char[] chars = "o".toCharArray();
                        writer.write(chars);
                        writer.flush();
                    } catch (IOException e) {
                        CommonServiceImpl.socket = new Socket(host, port);
                    }

//                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                Reader reader = new InputStreamReader(CommonServiceImpl.socket.getInputStream());

                    char chars[] = new char[512];
                    int len;
                    StringBuffer sb = new StringBuffer();
                    while ((len = reader.read(chars)) != -1) {
                        sb.append(new String(chars, 0, len));
                        break;
//                            if (new String(chars, 0, len).endsWith("?")){
//                                break;
//                            }
                    }
                    if (!sb.toString().equals("")) {
                        CommonServiceImpl.str = sb.toString();
                    } else {
                        CommonServiceImpl.socket = new Socket(host, port);
                    }
                    sb.delete(0, sb.length());
                    System.out.println(CommonServiceImpl.str);
//                        String msg;//客户端发过来的信息.substring(0,sb.length()-1)
//                        while ((msg = bufferedReader.readLine()) != null) {
//                            CommonServiceImpl.str=msg;
//                            System.out.println(CommonServiceImpl.str);
////                        System.out.println("##客户端：" + msg);
//                        }
                } catch (Exception e) {
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}